/**

Copyright 2010 ThreeTags (www.threetags.com)

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of ThreeTags nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THREETAGS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

package com.threetags.link.gae.db;

import java.util.Random;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class ShardedCounter {
	
	static {
		ObjectifyService.register(DatastoreCounter.class);
		ObjectifyService.register(DatastoreCounterShard.class);
	}
	
    private final String                m_id            ;
    private final DatastoreCounter      m_counter       ;
    private final Objectify             m_ofy           ;
    
    public static ShardedCounter get( String name ) {
        return get(null, name, 1);
    }
    
    public static ShardedCounter get( String name, int nShards ) {
        return get(null, name, nShards);
    }
    
    public static
    ShardedCounter get( Objectify ofy, String name ) {
        return get( ofy, name, 1 );
    }
    
    public static 
    ShardedCounter get( Objectify ofy, String name, int nShards ) {
        return new ShardedCounter(ofy, name, nShards);
    }
    
    private ShardedCounter(Objectify ofy, String name, int nShards) {
        if( ofy == null ) ofy = ObjectifyService.begin();
        m_ofy           = ofy   ; 
        m_id            = name  ;
        
        DatastoreCounter counter = null;
        
        try {
            counter = m_ofy.get( DatastoreCounter.class, m_id );
        } catch( Exception e ) {
        }
        
        if(( counter != null ) && ( counter.getShardCount() >= nShards ) ) {
            m_counter = counter;
            return;
        }

        // we need to create some shards, and probably the counter itself
        // for this, we either re-use the outer TX, or create our own
        Objectify innerOfy = null;
        if( ( m_ofy.getTxn() == null ) || ( !m_ofy.getTxn().isActive()) ) {
            innerOfy = ObjectifyService.beginTransaction();
        } 
        
        try {
            
            if( counter == null ) {
                counter = new DatastoreCounter(m_id, 0);
                System.out.println( "created DatastoreCounter(): " + m_id );
            }
                
            for( int n = counter.getShardCount(); n < nShards; ++n )
                if( innerOfy == null )
                    m_ofy.put( new DatastoreCounterShard(m_id, n) );
                else
                    innerOfy.put(new DatastoreCounterShard(m_id, n ));
            
            counter.setShardCount(nShards);
            
            if(innerOfy == null) 
                m_ofy.put(counter);
            else
                innerOfy.put(counter);
            
            if( innerOfy != null ) {
                innerOfy.getTxn().commit();
                // need to attach m_counter to m_ofy
                counter = m_ofy.get( DatastoreCounter.class, m_id );
            } 

            m_counter = counter;
        
        } 
        finally {
            if( ( innerOfy != null ) && ( innerOfy.getTxn().isActive() ) )
                innerOfy.getTxn().rollback();
        }
        
    } // ShardedCounter() ctor

    public long getCount() {
        long sum = 0;

        Iterable<DatastoreCounterShard> shards = 
            m_ofy.query(DatastoreCounterShard.class).ancestor(m_counter).list();
        
        assert(shards != null);
        
        for( DatastoreCounterShard shard : shards )
            sum += shard.getCount();

        return sum;
    } // getCount()
    
    public static final String getShardID( String sCounterName, int nShardNum ) 
    {
        return sCounterName + "___" + Integer.toHexString(nShardNum);
    }

    public void increment() {
        increment(1);
    }

    public void increment(long count) {

        int shardCount = m_counter.getShardCount();

        // Choose the shard randomly from the available shards.
        Random generator = new Random();
        int shardNum = generator.nextInt(shardCount);
    
        increment( count, shardNum );
    } // increment()
    
    private void increment( long count, int shardNum ) {
        DatastoreCounterShard shard = m_ofy.get(
                new Key<DatastoreCounterShard>( 
                    new Key<DatastoreCounter>(DatastoreCounter.class, m_id), 
                    DatastoreCounterShard.class, 
                    getShardID(m_id, shardNum)
                )
            );
        
        shard.increment(count);
        m_ofy.put(shard);
    }

    public void incrementSerial(long count) {
        increment( count, 0 );
    }
    
} // class ShardedCounter
